package cn.hm.controller;

import cn.hm.entity.User;
import cn.hm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Mxb
 * @version 1.0
 * @date 2020/7/16 10:47
 */
@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    //@RequestMapping(value = "/login-success", produces = {"text/plain;charset=UTF-8"})
    @RequestMapping(value = "/login-success")
    public String loginSuccess() {
        String username = getUser();

        return username + "：登录成功";
    }

    /**
     * 访问资源r1
     *
     * @return
     */
    @PreAuthorize("hasAuthority('p1')")  //访问前拦截，拥有p1权限可以访问
    @GetMapping(value = "/r/r1", produces = "text/plain;charset=UTF-8")
    public String r1() {
        String username = getUser();
        return username+"访问资源r1";
    }

    /**
     * 访问资源r2
     *
     * @return
     */
    @GetMapping(value = "/r/r2", produces = "text/plain;charset=UTF-8")
    public String r2() {
        String username = getUser();
        return username+"访问资源r2";
    }

    /**
     * 获取用户信息
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/info/{id}")
    public User info(@PathVariable Long id) {
        User user = userService.selectByPrimaryKey(id);
        return user;
    }

    /**
     * 获取用户信息
     * @return
     */
    private String getUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (!authentication.isAuthenticated()) {
            return null;
        }
        Object principal =authentication.getPrincipal();
        String username = null;

        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();

        } else {
            username = principal.toString();
        }
        return username;
    }
}
